package com.dx_society.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dx_society.domain.Societies;
import com.dx_society.domain.SocietyNotice;
import com.dx_society.domain.User;
import com.dx_society.dto.Result;
import com.dx_society.dto.UserDTO;
import com.dx_society.mapper.SocietiesMapper;
import com.dx_society.service.SocietyNoticeService;
import com.dx_society.mapper.SocietyNoticeMapper;
import com.dx_society.utils.UserHolder;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
* @author 韶光善良君
* @description 针对表【dx_society_notice(社团公告)】的数据库操作Service实现
* @createDate 2024-07-01 10:15:30
*/
@Service
public class SocietyNoticeServiceImpl extends ServiceImpl<SocietyNoticeMapper, SocietyNotice>
    implements SocietyNoticeService{
    @Resource
    private Snowflake snowflake;
    @Resource
    private SocietiesMapper societiesMapper;
    @Override
    public Result pubNotice(String context) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请先登录");
        } else if (user.getRole() != 1) {
            return Result.fail("权限不足");
        }
        QueryWrapper<Societies> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so_master_id", user.getUserid());
        Societies soMasterId = societiesMapper.selectOne(queryWrapper);

        Long soId = soMasterId.getSoId();
        Long noticeId =snowflake.nextId();
        SocietyNotice societyNotice = new SocietyNotice();
        societyNotice.setId(noticeId);
        societyNotice.setContext(context);
        societyNotice.setSoId(soId);
        return save(societyNotice) ? Result.ok() : Result.fail("发布失败");
    }

    @Override
    public Result deleteNotice(Long id) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请先登录");
        } else if (user.getRole() != 1) {
            return Result.fail("权限不足");
        }
        QueryWrapper<Societies> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("so_master_id", user.getUserid());
        Societies soMasterId = societiesMapper.selectOne(queryWrapper);

        SocietyNotice byId = getById(id);
        if (byId == null) {
            return Result.fail("公告不存在");
        }else if(!Objects.equals(byId.getSoId(), soMasterId.getSoId())){
            return Result.fail("权限不足");
        }
        removeById(id);
        return Result.ok("删除公告成功");
    }


}




